package com.example.controller;

import com.example.entity.Course;
import com.example.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @GetMapping("/list")
    public String list(Model model) {
        List<Course> courses = courseService.getAllCourses();
        model.addAttribute("courses", courses);
        return "course/list";
    }

    @GetMapping("/add")
    public String toAddPage() {
        return "course/add";
    }

    @PostMapping("/add")
    public String add(Course course) {
        courseService.addCourse(course);
        return "redirect:/course/list";
    }

    @GetMapping("/edit/{courseid}")
    public String toEditPage(@PathVariable("courseid") Integer courseid, Model model) {
        Course course = courseService.getCourseById(courseid);
        model.addAttribute("course", course);
        return "course/edit";
    }

    @PostMapping("/edit")
    public String edit(Course course) {
        courseService.updateCourse(course);
        return "redirect:/course/list";
    }

    @GetMapping("/delete/{courseid}")
    public String delete(@PathVariable("courseid") Integer courseid) {
        courseService.deleteCourse(courseid);
        return "redirect:/course/list";
    }

    @RequestMapping("findByPage")
    public String findByPage(int page, Model model) {
        int pageNum = 3;
        List<Course> courseList = courseService.findCoursesByPage(page, pageNum);
        int totalPage = courseService.totalPage(pageNum);

        model.addAttribute("courseList", courseList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", totalPage);
        return "user/home";
    }

    @GetMapping("/detail/{courseid}")
    public String detail(@PathVariable("courseid") Integer courseid, Model model) {
        Course course = courseService.getCourseById(courseid);
        model.addAttribute("course", course);
        return "course/detail";
    }
}